import {
    sendCommandCmd,
    sendCommand,
    sendEndLive,
    getLiveInfo,
    getIllegalList,
    isSilence, sendLotter
} from '@/api/live/screen';
import {
    createYanjinci,
    delYanjinci
} from '@/api/live/yanjincigroup';

import {getShuZiRenData} from '@/api/live/shuziren';
import {
    getSalerList,
    getLineUser,
    getPinglunList,
    sendCourseSellCommand,
    sendCourseSellCmd,
    getSalerInvatationUserIds
} from '@/api/live/liveonline';

import UserInfo from '../action/components/UserInfo.vue';
import YaoQing from '../action/components/YaoQing.vue';
import PingLun from '../action/components/PingLun.vue';
import GuanKong from '../action/components/GuanKong.vue';
import YingXiao from '../action/components/YingXiao.vue';
import YaoYue from '../action/components/YaoYue.vue';
import PayCourse from '../action/components/PayCourse.vue';
import ChouJiang  from "../action/components/ChouJiang.vue";
import Notice from '../action/components/Notice.vue';
import Blackbord from '../action/components/Blackbord.vue';
import TencentCloudChat from '@tencentcloud/chat';
import ControlDigitalHuman from './components/controlDigitalHuman.vue';
import ControlPay from './components/controlPay.vue';
import ControlSignIn from './components/controlSignIn.vue';
import ControlCar from './components/controlCar.vue';
import ControlEndLive from './components/controlEndLive.vue';
import LiveMsg from './components/liveMsg.vue';
import LiveSilenceMsg from './components/liveSilenceMsg.vue';
import LiveLexicon from './components/liveLexicon.vue';
import LiveSignIn from './components/liveSignIn.vue';
import PersButton from '@/components/PersButton.vue';
import { getToken } from '@/common/token';
import fa from "element-ui/src/locale/lang/fa";

import SelectImg from '@/components/select-img';


export default {
    name: 'LiveScreenControl',
    components: {
        UserInfo,
        YaoQing,
        PingLun,
        GuanKong,
        YingXiao,
        YaoYue,
        PayCourse,
        Notice,
        Blackbord,
        ChouJiang,

        ControlDigitalHuman,
        ControlPay,
        ControlSignIn,
        ControlCar,
        ControlEndLive,
        LiveMsg,
        LiveSilenceMsg,
        LiveLexicon,
        LiveSignIn,
        PersButton,
        SelectImg
    },
    data() {
        return {
            imgList: [],
            isLoading: false,
            isMyselfLoading: false,
            isDigitalLoading: false,
            IsShowPicDig: false,
            imgnum: 10, //选择图片数量,
            isMsgScroll: true,  //消息滚动条
            xiaoheiban_textInput: '',//小黑板文字内容
            activeName2: 'gonggao2',
            show_gonggao: false,  //公告弹窗显示与否
            show_anniu_gonggao: false,  //右下角公告按钮显示与否
            gonggao_textInput: '',  //公告内容
            activeName: 'userinfo',
            activeCommentsName: 'first',
            loading: false,
            search_course_name: '', //课程搜索
            title: null,  // 直播标题
            live_id: this.$route.query.liveId,  // 直播id
            start_time: null,  // 开播时间
            end_time: null,  // 关播时间
            status: 0,  // 直播状态
            online_person: 0,  // 在线人数
            anchor_nickname: '',
            anchor_head_img_url: '',
            member_id: '',
            member_sign: '',
            admin_id: 'administrator',
            admin_sign: '',
            is_im_admin: null,
            control_id: '',
            control_sign: '',
            tutor_id: '',
            tutor_sign: '',
            tutor_name: '助教老师',
            tutor_avatar: 'http://1251993779.vod2.myqcloud.com/0f0890f7vodcq1251993779/13dd09e91397757889072110054/euaZ4tp6rFUA.jpg',
            tutor_role: '场控',
            live_background_image: null,  // 背景图片
            chat: null,  // 腾讯云聊天室实例
            group_id: null,  // 群组id
            SDKAppID: 1600036635,
            clientUsers: '',  // 客户账号
            userList: [],  // 助教账号列表
            statusInfo: [],  // 控制初始值
            last_msg_list: [],  // 消息列表全部
            msgList: [],  // 消息列表
            msgListAll: [],  // 全部消息列表
            isMsgLoading: false, // 消息加载状态
            msgPage: 1, // 消息当前页数
            msgMaxPage: 0, // 消息最大页数
            msgSize: 20, // 消息当前页条数
            msgTotalSize: 0, // 消息总条数
            msgHideList: [],  // 隐藏消息列表
            msgForbidList: [],  // 禁言消息列表
            msgIllegalList: [],  // 违禁消息列表
            msgLexiconList: [],  // 违禁词库
            groupLexiconList: [],  // 违禁词组列表
            groupLexiconValue: 0,  // 违禁词组选中值
            goodsList: [],  // 商品列表
            userLiveInfo: [],  // 直播端用户信息
            requestUrl:"",
            iframeParams: null,  // iframe参数
            textUserInput: '',  // @他内容
            textInput: '',  // 发言内容
            textFrequencyInput: 1,  // 发言水军条数
            textDigitalInput: '',  // 发言水军内容
            textLexiconInput: '',  // 添加违禁词内容
            explain_id: null,  // 课程id
            switch_online_people_show: false, //在线人数显示
            switch_little_yellow_car_show: false, //小黄车显示
            switch_order_entrance_show: false, //用户订单入口显示
            operation_delay_num: 0, //操作延迟时间
            switch_all_silence: false, //全局禁言
            switch_hide_nickname: false, //隐藏昵称
            switch_inventory_show: false, //仅剩库存
            switch_selling_show: false, //正在热卖
            online_count_num: 0,  // 在线人数
            selling_num: 0,  // 已售
            inventory_num: 0,  // 库存
            isCardId: 0,  // 弹卡ID
            isCardStatus: false,  // 弹卡状态
            isSellOutId: 0,  // 售空ID
            isSellOutStatus: false,  // 售空状态
            isPopUpId:0, //弹窗ID
            isPopUpStatus:false, //弹窗状态
            isDigitalHumanCar: false,  // 是否数字人浏览小黄车弹框
            isDigitalHumanComment: false,  // 是否数字人评论弹框
            isDigitalHumanPay: false,  // 是否数字人下单弹框
            isDigitalHumanSignIn: false,  // 是否数字人进场弹框
            isDigitalHumanEndLive: false,  // 显示小黄车弹框
            switch_hide_digit_man: false,  // 是否隐藏数字人
            wss: null,  // websocket实例
            wss_url: null,  // websocket地址
            wsReconnectTimer: null,  // websocket重连定时器
            sendUserType: false,  // 发送人类型切换
            handoffUserType: false,  // 切换人类型切换
            randomUser: null,  // 随机水军用户
            randomUserNick: null,  // 随机水军昵称显示
            digit_person_list: [],  // 水军列表
            digit_person_total: 0,  // 水军总数
            

            polling: 0,  // 轮询秒数
            lineHeight: 16, //跟字体大小和wraper的高度相关！
            // 秒
            arr1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index1: 0,
            arr2: [0, 1, 2, 3, 4, 5],
            index2: 0,
            // 分
            arr3: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index3: 0,
            arr4: [0, 1, 2, 3, 4, 5],
            index4: 0,
            // 时
            arr5: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index5: 0,
            arr6: [0, 1, 2],
            index6: 0,
            //日
            arr7: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index7: 1,
            arr8: [0, 1, 2, 3],
            index8: 0,
            //月
            arr9: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index9: 1,
            arr10: [0, 1],
            index10: 0,
            //年
            arr11: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index11: 4,
            arr12: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index12: 2,
            arr13: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index13: 0,
            arr14: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index14: 2,

            // 用时-秒
            arr01: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index01: 0,
            arr02: [0, 1, 2, 3, 4, 5],
            index02: 0,
            // 用时-分
            arr03: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index03: 0,
            arr04: [0, 1, 2, 3, 4, 5],
            index04: 0,
            // 用时-时
            arr05: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            index05: 0,
            arr06: [0, 1, 2],
            index06: 0,
            
            // 倒计-秒
            pourArr1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            pour1: 0,
            pourArr2: [0, 1, 2, 3, 4, 5],
            pour2: 0,
            // 倒计-分
            pourArr3: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            pour3: 0,
            pourArr4: [0, 1, 2, 3, 4, 5],
            pour4: 0,
            // 倒计-时
            pourArr5: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            pour5: 0,
            pourArr6: [0, 1, 2],
            pour6: 0,
            // 倒计-天
            pourArr7: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            pour7: 0,
            pourArr8: [0, 1, 2, 3],
            pour8: 0,

            gonggao_show: false,   //公告显隐
            heiban_show: false,   //公告显隐
        }
    },
    created() {
        // 在组件创建后执行
        this.init();
    },
    mounted() {
        // 在组件挂载后执行
    },
    updated() {
        // 在组件更新后执行
    },
    beforeDestroy() {
        // 在组件销毁前执行
        // 在组件销毁前移除IM监听事件处理函数
        this.removeEvents();  // 移除事件监听
        this.disconnect();  // 断开连接
    },
    watch: {
        index5(newVal) {
            // 超过24小时
            if (this.index6 === 2 && newVal === 4) {
                console.log('[control] out')
                for (let i = 1; i < 7; i++) {
                    this[`index${i}`] = 0
                }
            }
        },
        pour1(newVal) {
            if (newVal === 0 && this.pour2 === 0 && this.pour3 === 0 && this.pour4 === 0 && this.pour5 === 0 && this.pour6 === 0 && this.pour7 === 0 && this.pour8 === 0) {
                console.log('[control] pour=0');
                // this.status = 1;
                setTimeout(() => {
                    this.init(0);
                }, 500);
            }
        },
        polling(newVal) {
            // 每分钟刷新数据
            if (newVal === 2) {
                // console.log('[control] polling=2');
                this.polling = 0;
                let scrollView = this.$refs.liveMsgRef.getScroll();
                if ((scrollView.scrollHeight - scrollView.scrollTop - 490) > 5) {
                    if (this.isMsgScroll) this.isMsgScroll = false;
                } else {
                    if (!this.isMsgScroll) this.isMsgScroll = true;
                }
                // console.log('[control] scrollView:', scrollView.scrollHeight - scrollView.scrollTop - 490, this.isMsgScroll);
                
                
            }
        }
    },
    methods: {
        /*************************      选择图片      **************************** */
        delimg(item) {

            for (let i = 0; i < this.imgList.length; i++) {
                const element = this.imgList[i];
                if (element == item) {
                    this.imgList.splice(item, 1);
                    console.log('delimg:' + item);
                }

            }
        },
        openUploadDial: function () {

            this.IsShowPicDig = true;
            
        },
        cleanDiaglog: function (shows) {
            this.IsShowPicDig = false;
        },
        selectImgs: function (res) {

            console.log(res);
            this.IsShowPicDig = true;
            for (let i = 0; i < res.length; i++) {
                this.imgList.push(res[i].urls);
            }
             
        },
        /******************************** tab标签 ************************************/

        dianji_tab_heiban(tab, event) {
            console.log('[control] dianji_tab_heiban');
            console.log(this.activeName2);
            this.activeName2 = tab.name;
        },

        dianji_tab(tab, event) {
            console.log('[control] dianji_tab');
            console.log('[control] ', this.activeName);
            this.activeName = tab.name;
        },
        // 评论tab标签点击
        handleClick(e) {
            console.log('[control] tab', e.index, e.label);
            switch (e.index) {
                case '0':
                    //this.activeName = 'first';
                    this.tabIndex1();
                    break;
                case '1':
                    // this.activeName = 'second';
                    this.tabIndex1();
                    break;
                case '2':
                    // this.activeName = 'third';
                    this.tabIndex2();
                    break;
                case '3':
                    // this.activeName = 'fourth'
                    this.tabIndex3();
                    break;
                case '4':
                    // this.activeName = 'fifth';
                    this.tabIndex4();
                    break;
                case '5':
                    // this.activeName = 'sixth';
                    this.tabIndex5();
                    break;
                case '6':
                    // this.activeName = 'seventh';
                    break;
            }
        },
        // 评论第1个tab标签，全部评论列表
        tabIndex1() {
            setTimeout(() => {
                this.$refs.liveMsgRef.autoScroll();
            }, 500);
            return false;
        },
        // 评论第2个tab标签，隐藏消息列表
        tabIndex2() {
            return false;
        },
        // 评论第3个tab标签，禁言消息列表
        tabIndex3() {
            setTimeout(() => {
                this.$refs.liveForbidRef.autoScroll();
            }, 500);
            return false;
        },
        // 评论第4个tab标签，违禁词列表
        tabIndex4() {
            return false;
        },
        // 评论第5个tab标签，违禁词库列表
        tabIndex5() {
            getIllegalList({
                liveId: this.live_id
            }).then(res => {
                console.log('[control] msgLexiconList', res.data);
                if (res.code === 200) {
                    this.msgLexiconList = res.data.list;
                    this.groupLexiconList = res.data.group;
                    this.groupLexiconValue = res.data.group[0].id;
                }
            })
            return false;
        },
        /******************************** 直播信息 ************************************/
        init(dateInit = 1) {
            // 获取直播信息
            getLiveInfo({
                liveId: this.$route.query.liveId
            }).then((res) => {
                if (res.code === 200) {
                    console.log('[control] --获取直播信息成功!', res.data);
                    this.title = res.data.title;
                    this.start_time = res.data.start_time;
                    this.end_time = res.data.end_time;
                    this.SDKAppID = res.data.im_appid;
                    this.status = res.data.status;
                    this.online_person = res.data.total_online_user_num;
                    this.guankan_renshu = res.data.guankan_renshu;
                    this.statusInfo = res.data.status_info;
                    this.anchor_nickname = res.data.teacher_name;
                    this.anchor_head_img_url = res.data.face_url;
                    this.live_background_image = res.data.bg_url;
                    this.group_id = res.data.chatroom_group_id;
                    this.userLiveInfo = res.data.userInfo_for_live;
                    console.log('[control] userLiveInfo', this.userLiveInfo);
                    this.member_id = this.userLiveInfo.member_id;
                    this.member_sign = this.userLiveInfo.member_sign;
                    this.admin_id = this.userLiveInfo.admin_id;
                    this.admin_sign = this.userLiveInfo.admin_sign;
                    this.control_id = this.userLiveInfo.control_id;
                    this.control_sign = this.userLiveInfo.control_sign;
                    this.is_im_admin = this.userLiveInfo.is_im_admin;
                    this.tutor_id = this.userLiveInfo.user_id;
                    this.tutor_name = this.userLiveInfo.user_name;
                    this.tutor_avatar = this.userLiveInfo.user_avatar;
                    this.tutor_sign = this.userLiveInfo.user_sign;
                    this.userList = res.data.userList;
                    this.goodList = res.data.good_info;
                    this.goodsList = JSON.parse(res.data.course_sale_ids);
                    this.goodsList = this.goodsList.map(item => Object.assign(item, this.goodList[item.id]));
                    console.log('[control] goodsList', this.goodsList);
                    
                    this.wss_url = `wss://${res.data.wss_host}/live_control?liveId=${this.live_id}&Authorization=${getToken()}`;
                    this.msgList = this.msgDispose(res.data.last_msg_list);
                    this.msgListAll = this.msgDispose(res.data.last_msg_list_all);
                    this.requestUrl = res.data.live_host +"/pages/animate/live";
                    
                    
                    // let last_msg_list = this.msgDispose(res.data.last_msg_list);
                    // this.msgTotalSize = last_msg_list.length; // 消息总条数

                    // this.last_msg_list = this.msgDispose(res.data.last_msg_list);
                    // this.msgTotalSize = this.last_msg_list.length; // 消息总条数

                    // this.msgMaxPage = Math.ceil(this.msgTotalSize/this.msgSize); // 消息最大页数
                    // this.msgPage = this.msgMaxPage; // 当前页
                    // this.msgList = this.msgPages(this.last_msg_list, this.msgMaxPage);
                    this.msgIllegalList = this.msgDispose(res.data.last_illegal_msg_list);
                    this.msgForbidList = this.msgDispose(res.data.last_silence_msg_list);
                    this.msgHideList = this.msgDispose(res.data.last_hide_msg_list);
                    console.log('[control] 初始化消息列表---', this.msgList);
                    console.log('[control] 初始化违禁词消息列表---', this.msgIllegalList);
                    console.log('[control] 初始化禁言消息列表---', this.msgForbidList);
                    console.log('[control] 初始化隐藏消息列表---', this.msgHideList);
                    

                    if (dateInit) {
                        this.iframeParams = `liveId=${this.live_id}&tutorId=${this.tutor_id}&front_token=${this.userLiveInfo.front_token}`;
                        this.init_digit_person_list();  // 初始化数字人列表
                        this.getTime(new Date());  // 获取当前时间并设置时间计数器
                        this.chatInit();  // 初始化聊天
                    }
                    this.init_status();  // 初始化控制状态dd
                    this.webSocketInit();  // 初始化websocket
                    if (this.switch_hide_digit_man) {
                        this.msgList = this.msgList.map(item => {
                            if (item.type === 3 || item.type === 4) {
                                item.is_digit_man = 1;
                            }
                            return item;
                        });
                    } else {
                        this.msgList = this.msgList.map(item => {
                            if (item.type === 3 || item.type === 4) {
                                item.is_digit_man = 0;
                            }
                            return item;
                        });
                    }
                } else {
                    console.warn('[control] 获取直播信息状态失败！', res);
                }
            }).catch((err) => {
                console.error('[control] 请求获取直播信息失败！', err);
            });
        },
        // 初始化数字人列表
        init_digit_person_list(type = 0) {
            if (type === 1) {
                // 随机
                if (this.digit_person_list.length > 0) {
                    const randomIndex = Math.floor(Math.random() * this.digit_person_list.length);
                    this.randomUser = this.digit_person_list[randomIndex];
                    this.randomUserNick = this.substrZhString(this.randomUser.nick, 8);
                }
            } else if (type === 2) {
                // 选择框变化
                this.randomUser = this.digit_person_list[this.randomUserNick];
                // console.log(this.randomUser);
            } else {
                // 初始化
                getShuZiRenData({
                    "size": 10000,
                    "page": 1,
                    "type": 1,
                    "input": '',
                    "flag": -1
                }).then((res) => {
                    // console.log('getShuZiRenData', res);
                    if (res.code === 200) {
                        this.digit_person_list = res.data.list;
                        this.digit_person_total = res.data.total;
                        // console.log('getShuZiRenData-list', this.digit_person_list);
                        this.init_digit_person_list(1);
                    }
                })
            }
            return false;
        },
        //设置商品是否售罄
        setCourseSellOut(good, status) {
            var msg = '';
            if(status){
                msg = '确定设置为已售罄?';
            }else{
                msg = '确定取消已售罄?'
            }
            this.$confirm(msg, '提示', {
                
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                
            }).then(() => {
                
                const command = {
                    command: 'courseSellStatus',
                    status: status
                };
                sendCourseSellCommand({
                    chartId: this.group_id,
                    command: JSON.stringify(command)
                }).then((res) => {
                    console.log('[control] 发送显示商品是否售罄信息：', res);
                    this.$message.success('发送请求成功');
                }).catch((err) => {
                    console.error('[control] err', err);
                });
                //状态储存
                sendCourseSellCmd({
                    liveId: this.live_id,
                    command: 'showCourseSellStatus',
                    status: status ? '1' : '0',
                    params: {
                        liveId: this.live_id,
                        operator_account: this.member_id,
                        operator_name: this.tutor_name,
                        operator_role: this.tutor_role,
                        operator_type: status ? 13 : 12,
                        goodsId:good.id, //记录课程id,只记录设置售罄的课程id
                        status: status ? '1' : '0'
                    }
                }).then((res) => {
                    console.log('[control] 显示商品是否售罄状态储存：', res);
                    this.isCardId = good.id;
                    this.isCourseSellStatus = status;
                    //location.reload();
                    //更新设置状态
                    console.log('[control] sell_out_goods_id_list：', res.data.sell_out_goods_id_list);
                    if(res.data){
                        this.sell_out_goods_id_list = res.data.map(Number);
                    }else{
                        res.data.sell_out_goods_id_list = [];
                    }
                    
                    
                }).catch((err) => {
                    console.error('[control] err', err);
                });
                //若是隐藏商品，则同步隐藏弹卡
                // if(!this.isCourseSellStatus){
                //     this.isCourseSellStatus = false;
                //     this.goodsList.forEach(element => {
                //         if(element.id == this.isCardId ){
                //             this.setCourseSellOut(element , this.isCourseSellStatus);
                //         }
                //     });
                //
                // }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
            return false;
        },
        /*********************** websocket ************************************/
        webSocketInit() {
            this.wss = new WebSocket(this.wss_url);
            this.wss.onopen = (event) => {
                console.log('[control] WebSocket连接已打开！');
                // 在这里你可以发送数据到服务器
            };
            this.wss.onmessage = (event) => {
                // console.log('[control] 收到的WebSocket消息:', event.data);
                // 处理从服务器接收到的数据
                let data = JSON.parse(event.data);
                this.goodList = data.good_info;
                this.goodsList = this.goodsList.map(item => Object.assign(item, this.goodList[item.id]));
                if (data.total_online_user_num !== this.online_person) this.online_person = data.total_online_user_num;
                if (data.status !== this.status) this.status = data.status;
                if (data.status_info !== this.statusInfo) {
                    this.statusInfo = data.status_info;
                    this.init_status();
                }
            };
            this.wss.onerror = (error) => {
                // 连接错误
                console.error('[control] WebSocket Error: ', error);
                if (!this.wsReconnectTimer) {
                    this.wsReconnect();
                }
            };
            this.wss.onclose = (event) => {
                // 连接关闭的回调
                this.wsReconnectTimer && clearTimeout(this.wsReconnectTimer);
                this.wsReconnectTimer = null;
                if (event.wasClean) {
                    console.log('[control] WebSocket 连接已关闭, code=', event.code, 'reason=', event.reason);
                } else {
                    console.error('[control] WebSocket 连接关闭失败', event);
                }
            };
        },
        wsReconnect() {
            console.log('[control] WebSocket 重新连接中...');
            //间隔3秒重连
            this.wsReconnectTimer = setInterval(() => {
                let timestamp = parseInt(new Date().getTime() / 1000);
                if (timestamp > this.end_time) {
                    clearTimeout(this.wsReconnectTimer); //关闭定时器
                    this.wsReconnectTimer = null;
                } else {
                    this.webSocketInit();
                }
            }, 3000);
        },
        /*********************** chat 腾讯IM ************************************/
        //初始化
        chatInit() {
            const options = {
                SDKAppID: this.SDKAppID
            };
            //连接im
            this.chat = TencentCloudChat.create(options);
            //设置日志级别
            this.chat.setLogLevel(1);
            // IM绑定事件处理函数
            this.bindEvents();
            // 登录
            this.login();
        },
        // 登录
        login() {
            if (this.chat) {
                if (this.is_im_admin === 1) {
                    if (this.member_id === 'M_1') {
                        this.member_id = this.admin_id;
                        this.member_sign = this.admin_sign;
                    }
                }
                //登录账号
                console.log('[control] 登录用户：', this.member_id);

                const options = {
                    userID: this.member_id,
                    userSig: this.member_sign
                };
                this.chat.login(options).then((imResponse) => {
                    console.log('[control] im登录成功！', imResponse);
                    this.joinGroup();
                }).catch((err) => {
                    console.error('[control] im登录失败！', err);
                });
            } else {
                console.error('[control] im未初始化！不能登录！');
            }
        },
        // 登出
        logout() {
            if (this.chat) {
                this.chat.logout().then((imResponse) => {
                    console.log('[control] im登出成功！', imResponse);
                }).catch((err) => {
                    console.error('[control] im登出失败！', err);
                });
            }
        },
        // 关闭连接
        disconnect() {
            if (this.chat) {
                // 销毁 SDK 实例。SDK 会先 logout，然后断开 WebSocket 长连接，并释放资源。
                this.chat.destroy();
                console.log('[control] im连接已关闭');
            }
            if (this.wss) {
                // 关闭 WebSocket 连接
                this.wss.close();
            }
        },
        //加入直播群
        joinGroup() {
            if (this.chat) {
                const options = {
                    groupID: this.group_id,
                    type: TencentCloudChat.TYPES.GRP_AVCHATROOM
                }
                this.chat.joinGroup(options).then((imResponse) => {
                    switch (imResponse.data.status) {
                        case TencentCloudChat.TYPES.JOIN_STATUS_WAIT_APPROVAL:
                            console.log('[control] 等待管理员同意');
                            break;
                        case TencentCloudChat.TYPES.JOIN_STATUS_SUCCESS:
                            console.log('[control] 加群成功', imResponse.data.group); // 加入的群组资料
                            break;
                        case TencentCloudChat.TYPES.JOIN_STATUS_ALREADY_IN_GROUP:
                            console.log('[control] 已经在群中');
                            break;
                        default:
                            console.log('[control] 加群其他未知');
                            break;
                    }
                    // this.setGroupCounters(this.group_id);  // 创建计数key
                    // this.updateGroupProfile();
                }).catch((imError) => {
                    console.warn('[control] 加群 error:', imError); // 申请加群失败的相关信息
                });
            } else {
                console.error('[control] im未连接，无法加入直播群！');
            }
        },
        //退出群组
        quitGroup() {
            if (this.chat) {
                this.chat.quitGroup(this.group_id).then((imResponse) => {
                    // imResponse.data.groupID  退出成功的群 ID
                    console.log('[control] 退出群组成功');
                }).catch((imError) => {
                    console.warn('[control] 退出群组 error:', imError);
                });
            } else {
                console.error('[control] im未连接，无需退出群组');
            }
        },
        // 群全体禁言/解禁
        updateGroupProfile() {
            if (this.chat) {
                const options = {
                    groupID: this.group_id,
                    muteAllMembers: this.switch_all_silence
                };
                console.log('[control] updateGroupProfile', options);
                this.chat.updateGroupProfile(options).then((imResponse) => {
                    console.log('[control] 设置群组全体禁言成功', imResponse);
                    sendCommandCmd({
                        liveId: this.live_id,
                        command: 'showAllSilence',
                        params: {
                            liveId: this.live_id,
                            groupId: this.group_id,
                            status: this.switch_all_silence ? '1' : '0'
                        }
                    }).then((res) => {
                        console.log('[control] 发送全局禁言/解禁命令：', res);
                    }).catch((err) => {
                        console.error('[control] err', err);
                    });
                }).catch((imError) => {
                    this.switch_all_silence = !this.switch_all_silence;
                    console.warn('[control] 设置群组全体禁言 error:', imError);
                });
            } else {
                this.switch_all_silence = !this.switch_all_silence;
                console.error('[control] im未连接，无法设置群组全体禁言');
            }
        },
        // 设置管理员
        setGroupMemberRole() {
            if (this.chat) {
                const options = {
                    groupID: this.group_id,
                    userID: this.member_id,
                    role: 'Admin'
                };
                this.chat.setGroupMemberRole(options).then((imResponse) => {
                    console.log('[control] ' + this.member_id + '设置管理员成功', imResponse);
                }).catch((imError) => {
                    console.warn('[control] ' + this.member_id + '设置管理员 error:', imError);
                });
            } else {
                console.error('[control] im未连接，无法设置管理员');
            }
        },
        // 发送文本数据  
        sendText(msg, type, id, soleNo, msgTrue = '') {
            if (this.chat) {
                const obj = {
                    no: soleNo,
                    type: 2,
                    msg: msgTrue,
                    group_id: this.group_id
                };
                let options = {
                    to: id,
                    conversationType: type,
                    payload: { text: msg },
                    cloudCustomData: JSON.stringify(obj)
                };
                if (this.clientUsers) {
                    // 发送私聊
                    this.sendPrivateMsg(msg, this.member_id, this.clientUsers, JSON.stringify(obj));
                    return false;
                }
                console.log('[control] sendText:', options);
                const message = this.chat.createTextMessage(options);
                this.chat.sendMessage(message).then((imResponse) => {
                    console.log('[control] 发送文本消息成功', imResponse);
                    this.$message.success('发送请求成功');
                }).catch((imError) => {
                    console.warn('[control] 发送文本消息 error:', imError);
                    if (imError.code === 10016) {
                        //违禁词
                        this.$message.error('文本消息包含违禁词，发送失败');
                    } else if (imError.code === 10017) {
                        //禁言
                        this.$message.error('您已被禁言，无法发送消息');
                    }
                });
            } else {
                console.error('[control] im连接未建立，无法发送文本消息');
            }
        },
        // 发送私聊消息
        sendPrivateMsg(msg, sendUser, toUser, customData) {
            const params = {
                msg: msg,
                send_user: sendUser,
                to_user: toUser,
                custom_data: customData,
            };
            const command = {
                liveId: this.live_id,
                command: 'sendPrivateMessage',
                params: params
            };
            sendCommandCmd(command).then((res) => {
                console.log('[control] 发送私聊命令：', res);
                this.$message.success('发送请求成功');
                this.textInput = '';
                this.textUserInput = '';
                this.clientUsers = '';
                this.$refs.input_text_send.focus();
                this.$refs.input_text_send_silence.focus();
            }).catch((err) => {
                console.error('[control] 发送私聊 err', err);
            });
        },
        // 发送表情数据 
        sendFace(index, data, type, id) {
            if (this.chat) {
                const message = this.chat.createTextMessage({
                    to: id,
                    conversationType: type,
                    payload: {
                        text: message,
                        data: data
                    }
                });
                this.chat.sendMessage(message).then((imResponse) => {
                    console.error('[control] 发送表情消息成功', imResponse);
                }).catch((imError) => {
                    console.warn('[control] 发送表情消息 error:', imError);
                });
            } else {
                console.error('[control] im连接未建立，无法发送表情消息');
            }
        },
        // 点击@他按钮
        sendHe(item) {
            console.log('[control] @他', item);
            this.clientUsers = `${item.id}`;
            this.textUserInput = `@${item.nickname} ${item.msg} `;
            this.textInput = ' 回复：';
            return false;
        },
        // 清空@他消息
        endHeSendClean() {
            this.clientUsers = '';
            this.textUserInput = '';
            this.textInput = '';
        },
        //收消息异步处理
        asyncSendMsg(text, nick, id, avatar, icon, noJson) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    if (noJson.type === 1) {
                        const icon_id_text = id.substring(0, 2);
                        if (icon_id_text === 'A_'
                            || icon_id_text === 'C_'
                            || icon_id_text === 'M_'
                            || id === 'administrator') {
                            icon = '助教';
                        }
                        // if (id.includes('A_')
                        //     || id.includes('C_')
                        //     || id.includes('administrator')
                        //     || id.includes('M_')) {
                        //     icon = '助教';
                        // }
                    } else if (noJson.type === 2) {
                        icon = '助教';
                    } else if (noJson.type === 3) {
                        icon = '数字人';
                        if (this.switch_hide_digit_man) {
                            noJson.is_digit_man = 1;
                        }
                    } else if (noJson.type === 4) {
                        icon = '评论组';
                        if (this.switch_hide_digit_man) {
                            noJson.is_digit_man = 1;
                        }
                    } else if (noJson.type === 6) {
                        // 禁言消息
                        this.msgForbidList.push({
                            id: id,
                            msg: text,
                            nickname: nick,
                            avatar: avatar,
                            no: noJson.no,
                            icon_text: icon,
                            is_illegal: 0,
                            is_silence: 1,
                            is_hide: 0
                        });
                    } else if (noJson.type === 7 || noJson.msg) {
                        // 违禁词消息
                        this.msgIllegalList.push({
                            id: id,
                            msg: text,
                            nickname: nick,
                            avatar: avatar,
                            no: noJson.no,
                            icon_text: icon,
                            is_illegal: 1,
                            is_silence: 0,
                            is_hide: 0
                        });
                    } else if (noJson.type === 47) {
                        // 评论组违禁词消息
                        console.log('评论组违禁词消息');
                        icon = '评论组';
                        if (this.switch_hide_digit_man) {
                            noJson.is_digit_man = 1;
                        }
                    }
                    if (!noJson.is_digit_man) {
                        this.$refs.liveMsgAllRef.sendMsg(text, nick, id, avatar, icon, noJson);
                        if (noJson.type != 4 && noJson.type != 3) {
                            this.$refs.liveMsgRef.sendMsg(text, nick, id, avatar, icon, noJson);
                        }
                    }
                    resolve();
                }, 300); // 延迟0.3秒钟
            });
        },
        //群提示处理
        asyncTipsProcessing(tip, nick) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    if (tip === 1) {
                        // 有成员加群
                        this.$refs.liveSignInRef.welcomeUser(nick);
                    } else if (tip === 10) {
                        // 封禁直播群群成员
                    } else if (tip === 11) {
                        // 解封直播群群成员
                    }
                    resolve();
                }, 2000); // 延迟2秒钟
            });
        },
        //命令处理
        asyncCommandProcessing(cod) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    if (cod.command === 'signIn') {
                        // 进场
                        this.$refs.liveSignInRef.welcomeUser(cod.nick);
                    }
                    resolve();
                }, 2000); // 延迟2秒钟
            });
        },
        /**************** 监听事件 *******************/
        //IM绑定监听事件
        bindEvents() {
            if (this.chat) {
                // 监听im连接打开事件
                this.chat.on(TencentCloudChat.EVENT.SDK_READY, this.onSdkReady.bind(this));

                // 监听WebSocket关闭
                this.chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, this.onSdkNotReady.bind(this));

                // 监听收到推送的单聊、群聊、群提示、群系统通知的新消息
                this.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.onMessageReceived.bind(this));

                // 监听群组计数器更改
                this.chat.on(TencentCloudChat.EVENT.GROUP_COUNTER_UPDATED, this.onGroupCounterUpdated.bind(this));

                // 监听群组事件
                // this.chat.on(TencentCloudChat.EVENT.GROUP_LIST_UPDATED, this.onGroupListUpdated.bind(this));

                // 监听网络状态发生改变
                this.chat.on(TencentCloudChat.EVENT.NET_STATE_CHANGE, this.onNetStateChange.bind(this));
            }

        },
        //IM移除监听事件
        removeEvents() {
            if (this.chat) {
                // 移除监听im连接打开事件
                this.chat.off(TencentCloudChat.EVENT.SDK_READY, this.onSdkReady.bind(this));

                // 移除监听WebSocket关闭 
                this.chat.off(TencentCloudChat.EVENT.SDK_NOT_READY, this.onSdkNotReady.bind(this));

                // 移除监听收到推送的单聊、群聊、群提示、群系统通知的新消息
                this.chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.onMessageReceived.bind(this));

                // 移除监听群组计数器更改
                this.chat.off(TencentCloudChat.EVENT.GROUP_COUNTER_UPDATED, this.onGroupCounterUpdated.bind(this));

                // 移除监听群组事件
                // this.chat.off(TencentCloudChat.EVENT.GROUP_LIST_UPDATED, this.onGroupListUpdated.bind(this));

                // 移除监听网络状态发生改变
                this.chat.off(TencentCloudChat.EVENT.NET_STATE_CHANGE, this.onNetStateChange.bind(this));
            }
        },
        /*********************** 监听的回调函数 *********************************/
        // im连接打开时的回调函数  
        onSdkReady(event) {
            console.log('[control] im连接已打开！', event);
            // 消息类型：
            // C2C[私聊]TencentCloudChat.TYPES.CONV_C2C；
            // GROUP[群聊]TencentCloudChat.TYPES.CONV_GROUP
            // this.send('Hello world!', 'GROUP', 'group1');
        },
        // im关闭时的回调函数  
        onSdkNotReady(event) {
            console.log('[control] im连接已关闭！', event);
            // 登录 
            this.chat.login({ userID: 'your userID', userSig: 'your userSig' });
        },
        // 收到推送的单聊、群聊、群提示、群系统通知的新消息时的回调函数
        async onMessageReceived(event) {
            // event.data - 存储 Message 对象的数组 - [Message]
            const messageList = event.data;
            for (const message of messageList) {
                if (message.type === TencentCloudChat.TYPES.MSG_TEXT) {
                    // 文本消息
                    const noJson = JSON.parse(message.cloudCustomData);
                    // console.log(message);
                    console.log('[control] [收]文本', noJson.group_id, this.group_id, message.from, message.payload.text);
                    // await this.asyncSendMsg(message.payload.text, message.nick, message.from, message.avatar, '铁粉', noJson);
                    if (noJson.group_id === this.group_id) {
                        await this.asyncSendMsg(message.payload.text, message.nick, message.from, message.avatar, '铁粉', noJson);
                    }
                    
                } else if (message.type === TencentCloudChat.TYPES.MSG_FACE) {
                    // 表情消息
                    // console.log('[control] [收]表情');
                } else if (message.type === TencentCloudChat.TYPES.MSG_GRP_TIP) {
                    // 群提示消息
                    // console.log('[control] [收]提示');
                    const { operationType } = message.payload;
                    await this.asyncTipsProcessing(operationType, message.nick);
                } else if (message.type === TencentCloudChat.TYPES.MSG_GRP_SYS_NOTICE) {
                    // 群系统通知
                    // console.log('[control] [收]通知');
                    const { operationType, userDefinedField } = message.payload;
                    // operationType - 操作类型 [255：用户自定义字段]
                    // userDefinedField - 用户自定义字段（对应 operationType 为 255）
                    // 使用 RestAPI 在群组中发送系统通知时，接入侧可从 userDefinedField 拿到自定义通知的内容。
                    if (operationType === 255) {
                        //命令处理
                        await this.asyncCommandProcessing(JSON.parse(userDefinedField))
                    }
                }
            }
            // console.log('[control] 收到服务器内容：', event.data);
        },
        // 计数器更改回调函数
        onGroupCounterUpdated(event) {
            const { groupID, key, value } = event.data;
            console.log('[control] 计数器回调：', event.data);
            // groupID - 群组 ID
            // key - 群计数器 key
            // value - 群计数器 key 对应的 value
        },
        // 群组事件回调函数
        onGroupListUpdated(event) {
            console.log('[control] 群组列表更新啦', event.data);
        },
        // 网络状态发生改变的回调函数
        onNetStateChange(event) {
            // event.data.state 当前网络状态，枚举值及说明如下：
            // TencentCloudChat.TYPES.NET_STATE_CONNECTED - 已接入网络
            // TencentCloudChat.TYPES.NET_STATE_CONNECTING
            // 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
            // TencentCloudChat.TYPES.NET_STATE_DISCONNECTED
            // 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
            console.log('[control] im网络变化啦', event.data.state);
        },
        /*********************** 工具 *********************************/
        // 中文字符串截取
        substrZhString(str, l = 1, s = 0, o = '...') {
            if (str.length > l) {
                let cropped = str.substr(s, l);
                if (/[^\u4e00-\u9fa5]$/.test(cropped)) {
                    // 如果最后一个支付不是完整的中文字符，则加1，补完整。
                    cropped = str.substr(s, l + 1);
                }
                return cropped + o;
            } else {
                return str;
            }
        },
        // 点击评论自动滚屏按钮
        autoscroll() {
            this.isMsgScroll = true;
            this.$refs.liveMsgRef.autoScroll();
            this.$refs.liveForbidRef.autoScroll();
        },
        //消息列表处理
        msgDispose(arr) {
            if (arr.length === 0) return [];
            arr = arr.map(item => {
                item.icon_text = '铁粉';
                if (item.hasOwnProperty('im_id')) {
                    if (item.im_id.startsWith('A_')
                        || item.im_id.startsWith('C_')
                        || item.im_id.indexOf('administrator') !== -1
                        || item.im_id.startsWith('M_')) {
                        item.icon_text = '助教';
                    } else if (item.im_id.indexOf('R_') !== -1 || item.type === 3) {
                        item.icon_text = '数字人';
                    } else if (item.im_id.indexOf('P_') !== -1 || item.type === 4) {
                        item.icon_text = '评论组';
                    } else if (item.type === 6) {
                        item.is_silence = 1;
                    } else if (item.type === 7) {
                        item.is_illegal = 1;
                    }
                } else {
                    if (item.type === 2) {
                        item.icon_text = '助教';
                    } else if (item.type === 3) {
                        item.icon_text = '数字人';
                    } else if (item.type === 4) {
                        item.icon_text = '评论组';
                    } else if (item.type === 6) {
                        item.is_silence = 1;
                    } else if (item.type === 7) {
                        item.is_illegal = 1;
                    }
                }
                return item;
            });
            return arr;
        },
        //消息列表处理
        msgSendDispose(arr) {
            if (arr.length === 0) return [];
            arr = arr.map(item => {
                item.icon_text = '铁粉';
                if (item.hasOwnProperty('im_id')) {
                    if (item.im_id.startsWith('A_')
                        || item.im_id.startsWith('C_')
                        || item.im_id.indexOf('administrator')
                        || item.im_id.startsWith('M_')) {
                        item.icon_text = '助教';
                    } else if (item.im_id.indexOf('R_') !== -1 || item.type === 3) {
                        item.icon_text = '数字人';
                    } else if (item.im_id.indexOf('P_') !== -1 || item.type === 4) {
                        item.icon_text = '评论组';
                    } else if (item.type === 6) {
                        item.is_silence = 1;
                    } else if (item.type === 7) {
                        item.is_illegal = 1;
                    }
                } else {
                    if (item.type === 2) {
                        item.icon_text = '助教';
                    } else if (item.type === 3) {
                        item.icon_text = '数字人';
                    } else if (item.type === 4) {
                        item.icon_text = '评论组';
                    } else if (item.type === 6) {
                        item.is_silence = 1;
                    } else if (item.type === 7) {
                        item.is_illegal = 1;
                    }
                }
                if(item.icon_text == '助教' || item.icon_text == '数字人' || item.is_illegal == 1 || item.is_silence == 1){
                    item.saler_name = '';
                }else{
                    item.saler_name = '';  //需匹配
                    if(this.allSalerInvationUserIds.hasOwnProperty(item.id)){
                        item.saler_name = this.allSalerInvationUserIds[item.id];
                    }
                }
                return item;
            });
            arr = arr.filter(item=>item.icon_text !=='数字人')  //数字人
                .filter(item=>item.is_illegal !==1)
                .filter(item=>item.is_silence !==1);
            // arr = arr.filter(item=>item.type === 3)   //数字人
            //     .filter(item=>item.im_id.indexOf('R_') !==-1)  //数字人
            //     .filter(item=>item.is_illegal !==1)
            //     .filter(item=>item.is_silence !==1);
            return arr;
        },
        //消息列表分页
        msgPages(array, page = 1, current = []) {

            //  msgList: [],  // 消息列表
            //  msgPage: 0, // 消息当前页数
            //  msgMaxPage: 0, // 消息最大页数
            //  msgSize: 50, // 消息当前页条数
            //  msgTotalSize: 0, // 消息总条数条数
            //  last_msg_list: 0, // 消息列表全部
            // let pages = (this.msgPage - 1) * this.msgSize;
            let startIndex = parseInt((page - 1) * this.msgSize);
            let endIndex = startIndex + this.msgSize;
            if ((this.msgTotalSize - startIndex) < this.msgSize) {
                startIndex = parseInt((page - 2) * this.msgSize);
                endIndex = this.msgTotalSize;
                this.msgPage = this.msgPage - 1;
            }
            console.log(`[control] 消息初始分页处理：page${page},start${startIndex},end${endIndex}[${startIndex + this.msgSize}],msgSize${this.msgSize},msgPage${this.msgPage},array${array.length}`);
            console.log(`[control] 消息初始分页处理：start${current.length}`);

            let list = array.slice(startIndex, endIndex);
            if (current && current.length > 0) {
                current = [...list, ...current];
                // current.unshift(list);
            } else {
                current = list;
            }
            console.log('[control] current', current);
            return current;

        },
        //消息列表分页回调
        loadMore() {
            // if (this.msgPage > this.msgMaxPage) return this.msgList;
            this.msgPage = this.msgPage - 1;
            if (this.msgPage < 1) {
                this.msgPage = 1;
                return this.msgList;
            }
            this.msgList = this.msgPages(this.last_msg_list, this.msgPage, this.msgList);
            setTimeout(() => {
                this.isMsgLoading = false;
            }, 500);
        },
        //群组计数key列表
        createGroupKey() {
            return {
                pv: 0,  // 浏览量
                uv: 0,  // 访客量
                order_pv: 0,  // 下单量
                order_uv: 0,  // 客单量
                pay_cart_pv: 0,  // 购物车浏览量
                pay_cart_uv: 0,  // 购物车访客量
                pay_order_pv: 0,  // 支付单量
                pay_order_uv: 0,  // 支付客单量
                pay_money: 0,  // 支付金额
                refund_money: 0,  // 退款金额
                refund_pv: 0,  // 退单量
                refund_uv: 0,  // 取消客单量
                refund_pay_pv: 0,  // 退款单量
                refund_pay_uv: 0,  // 退款客单量
                goods_pv: 0,  // 商品浏览量
                goods_uv: 0,  // 商品访客量
            };
        },
        //中英字符串截取
        subString(str, len, hasDot) {
            let newLength = 0;
            let newStr = '';
            let chineseRegex = /[^\x00-\xff]/g;
            let singleChar = '';
            let strLength = str.replace(chineseRegex, '**').length;
            for (let i = 0; i < strLength; i++) {
                singleChar = str.charAt(i).toString();
                if (singleChar.match(chineseRegex) != null) {
                    newLength += 2;
                } else {
                    newLength++;
                }
                if (newLength > len) {
                    break;
                }
                newStr += singleChar;
            }
            if (hasDot && strLength > len) {
                newStr += '…';
            }
            return newStr;
        },
        /*********************** 初始化控制状态 ***************************/
        init_status() {
            //弹卡
            if (this.statusInfo.hasOwnProperty('showPopCard') && this.statusInfo.showPopCard !== '0') {
                let showPopCard = JSON.parse(this.statusInfo.showPopCard);
                if (showPopCard.status === '1') {
                    this.isCardId = parseInt(showPopCard.goodsId);
                    this.isCardStatus = showPopCard.status === '1' ? true : false;
                } else {
                    this.isCardId = 0;
                    this.isCardStatus = false;
                }
            }
            //售空
            if (this.statusInfo.hasOwnProperty('showCourseSellStatus') && this.statusInfo.showCourseSellStatus !== '0') {
                let showCourseSellStatus = JSON.parse(this.statusInfo.showCourseSellStatus);
                for (let val in showCourseSellStatus) {
                    for (let item in this.goodsList) {
                        if (this.goodsList[item].id === showCourseSellStatus[val].goodsId) {
                            this.goodsList[item].isSellOutStatus = showCourseSellStatus[val].status
                        }
                    }
                }
            }
            //热卖
            if (this.statusInfo.hasOwnProperty('showHotSale') && this.statusInfo.showHotSale !== '0') {
                let showHotSale = JSON.parse(this.statusInfo.showHotSale);
                if (showHotSale.status === '1') {
                    this.switch_selling_show = true;
                } else {
                    this.switch_selling_show = false;
                }
                // if (parseInt(showHotSale.num) > this.selling_num) {
                //     this.selling_num = parseInt(showHotSale.num);
                // }
            }
            //库存
            if (this.statusInfo.hasOwnProperty('showStock') && this.statusInfo.showStock !== '0') {
                let showStock = JSON.parse(this.statusInfo.showStock);
                if (showStock.status === '1') {
                    this.switch_inventory_show = true;
                } else {
                    this.switch_inventory_show = false;
                }
                // if (parseInt(showStock.num) > this.inventory_num) {
                //     this.inventory_num = parseInt(showStock.num);
                // }
            }
            //隐藏昵称
            if (this.statusInfo.hasOwnProperty('showNickName') && this.statusInfo.showNickName !== '0') {
                let showNickName = JSON.parse(this.statusInfo.showNickName);
                if (showNickName.status === '1') {
                    this.switch_hide_nickname = true;
                } else {
                    this.switch_hide_nickname = false;
                }
            }
            //隐藏数字人/评论组 showDigitMan
            if (this.statusInfo.hasOwnProperty('showDigitMan') && this.statusInfo.showDigitMan !== '0') {
                let status_info_showDigitMan = JSON.parse(this.statusInfo.showDigitMan);
                if (status_info_showDigitMan.status === '1') {
                    this.switch_hide_digit_man = true;
                } else {
                    this.switch_hide_digit_man = false;
                }
            }
            //显示在线人数
            if (this.statusInfo.hasOwnProperty('showOnlineCount') && this.statusInfo.showOnlineCount !== '0') {
                let showOnlineCount = JSON.parse(this.statusInfo.showOnlineCount);
                if (showOnlineCount.status === '1') {
                    this.switch_online_people_show = true;
                } else {
                    this.switch_online_people_show = false;
                }
                // if (parseInt(showOnlineCount.num) > this.online_count_num) {
                //     this.online_count_num = parseInt(showOnlineCount.num);
                // }
            }
            //显示小黄车
            if (this.statusInfo.hasOwnProperty('showLittleYellowCar') && this.statusInfo.showLittleYellowCar !== '0') {
                let status_info_showLittleYellowCar = JSON.parse(this.statusInfo.showLittleYellowCar);
                //显示小黄车
                if (status_info_showLittleYellowCar.status === '1') {
                    console.log('[control] --showLittleYellowCar--');
                    this.switch_little_yellow_car_show = true;
                } else {
                    this.switch_little_yellow_car_show = false;
                }
            }
            //全局禁言/解禁
            if (this.statusInfo.hasOwnProperty('showAllSilence') && this.statusInfo.showAllSilence !== '0') {
                let status_all_silence = JSON.parse(this.statusInfo.showAllSilence);
                //全局禁言/解禁
                if (status_all_silence.status === '1') {
                    console.log('[control] --showAllSilence--');
                    this.switch_all_silence = true;
                } else {
                    this.switch_all_silence = false;
                }
            }



            //小黑板 显/隐
            if (this.statusInfo.hasOwnProperty('sendXiaoHeiBan') && this.statusInfo.sendXiaoHeiBan !== '0') {
                let sendXiaoHeiBan = JSON.parse(this.statusInfo.sendXiaoHeiBan);
                //全局禁言/解禁
                if (sendXiaoHeiBan.heiban_show) {
                    console.log('[control] --sendXiaoHeiBan--');
                    this.heiban_show = true;
                } else {
                    this.heiban_show = false;
                }
            }
        },
        /*********************** 消息 ***************************/
        async sendLiveDigitalMsg() {
            // 水军消息
            if (!this.textDigitalInput) {
                return false;
            }
            this.isDigitalLoading = true;
            if (this.textFrequencyInput > 1) {
                for (let i = 0; i < this.textFrequencyInput; i++) {
                    if (this.randomUser) {
                        await this.trollsBatch(this.randomUser);
                        if (!this.handoffUserType) {
                            this.init_digit_person_list(1);
                        }
                    }
                }
                this.textDigitalInput = '';
                this.$refs.input_text_digital_send.focus();
                return true;
            }
            if (this.randomUser) {
                this.trolls(this.randomUser);
            }
            return true;
        },
        sendLiveMsg() {
            console.log('[control] --sendLiveMsg--');
            if (!this.textInput) {
                return false;
            }
            this.isMyselfLoading = true;

            let msg = this.textUserInput + this.textInput;
            const dateNow = Date.now();
            const soleNo = this.$md5(this.member_id + dateNow + msg);
            let jsonData = {
                no: soleNo
            }
            isSilence({
                group_id: this.group_id,
                msg_text: msg,
                ccd: JSON.stringify(jsonData)
            }).then(ret => {
                this.isMyselfLoading = false;
                console.log('[control] isSilence-then:', ret);
                if (ret && ret.ErrorCode === 1) {
                    jsonData.msg = msg;
                    this.$refs.liveMsgRef.sendMsg(msg, this.tutor_name, this.member_id, this.tutor_avatar, '助教', jsonData);
                    this.sendText(msg, 'GROUP', this.group_id, soleNo, this.textInput);
                } else {
                    this.$refs.liveMsgRef.sendMsg(msg, this.tutor_name, this.member_id, this.tutor_avatar, '助教', jsonData);
                    this.sendText(msg, 'GROUP', this.group_id, soleNo);
                }
            }).catch(err => {
                this.isMyselfLoading = false;
                console.log('[control] isSilence-err:', err);
                this.$refs.liveMsgRef.sendMsg(msg, this.tutor_name, this.member_id, this.tutor_avatar, '助教', jsonData);
                this.sendText(msg, 'GROUP', this.group_id, soleNo);
            });
            this.textInput = '';
            // this.sendText(this.textInput, 'GROUP', this.group_id, soleNo);

        },
        // 水军发送消息
        trolls(data) {
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 14,
                digital_id: data.id,
                digital_name: data.nick,
                digital_img: data.touxiang_img,
                digital_content: this.textDigitalInput,
                identifier: 'R_' + data.id,
                msg: this.textDigitalInput
            };
            const command = {
                liveId: this.live_id,
                command: 'sendMessage',
                params: params
            };
            sendCommandCmd(command).then((res) => {
                this.isDigitalLoading = false;
                console.log('[control] 水军评论命令：', res);
                this.$message.success('发送请求成功');
                this.textDigitalInput = '';
                this.$refs.input_text_digital_send.focus();
                if (!this.handoffUserType) {
                    this.init_digit_person_list(1);
                }
            }).catch((err) => {
                this.isDigitalLoading = false;
                console.error('[control] 水军 err', err);
            });
        },
        //批量水军
        trollsBatch(data) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    const params = {
                        liveId: this.live_id,
                        operator_account: this.member_id,
                        operator_name: this.tutor_name,
                        operator_role: this.tutor_role,
                        operator_type: 14,
                        digital_id: data.id,
                        digital_name: data.nick,
                        digital_img: data.touxiang_img,
                        digital_content: this.textDigitalInput,
                        identifier: 'R_' + data.id,
                        msg: this.textDigitalInput
                    };
                    const command = {
                        liveId: this.live_id,
                        command: 'sendMessage',
                        params: params
                    };
                    sendCommandCmd(command).then((res) => {
                        this.isDigitalLoading = false;
                        console.log('[control] 水军评论命令：', res);
                        this.$message.success('发送请求成功');
                    }).catch((err) => {
                        this.isDigitalLoading = false;
                        console.error('[control] 水军 err', err);
                    });
                    resolve();
                }, 500); // 延迟0.5秒钟
            });
        },
        addLexicon() {
            //添加违禁词
            createYanjinci({
                liveId: this.live_id,
                name: this.textLexiconInput,
                groupid: this.groupLexiconValue
            }).then((res) => {
                if (res.code === 200) {
                    this.$message.success('添加成功');
                    this.textLexiconInput = '';
                    this.tabIndex4();
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        delLexicon(row) {
            //删除违禁词
            delYanjinci({
                id: row.id,
                liveId: this.live_id
            }).then((res) => {
                if (res.code === 200) {
                    this.$message.success('删除成功');
                    this.tabIndex4();
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        /*********************** 控制处理 *********************************/
        //延迟保存
        setDelayNum() {
            console.log('[control] operation_delay_num', this.operation_delay_num);
            if (this.operation_delay_num < 0) {
                this.operation_delay_num = 0;
            }
            this.$message.success('保存延迟成功');
        },
        //热卖
        imSetSelling() {
            if (!this.selling_num) {
                this.$message.error('请输入展示热卖数量');
                return false;
            }
            if (!this.isCardStatus) {
                this.$message.error('请先开启讲解');
                return false;
            }
            this.switch_selling_show = true;
            const command = {
                command: 'selling',
                num: this.selling_num,
                status: this.switch_selling_show
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送热卖命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            //状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showHotSale',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: 7,
                    num: this.selling_num,
                    status: '0'
                }
            }).then((res) => {
                console.log('[control] 热卖状态储存：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return false;
        },
        //库存
        imSetInventory() {
            if (!this.inventory_num) {
                this.$message.error('请输入展示库存数量');
                return false;
            }
            if (!this.isCardStatus) {
                this.$message.error('请先开启讲解');
                return false;
            }
            this.switch_inventory_show = true;
            const command = {
                command: 'inventory',
                num: this.inventory_num,
                status: this.switch_inventory_show
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送库存命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            //状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showStock',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: 8,
                    num: this.inventory_num,
                    status: '0'
                }
            }).then((res) => {
                console.log('[control] 库存状态储存：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return false;
        },
        //弹窗
        imPopUp(good, status) {
            // this.explain_id = good.id;
            const command = {
                command: 'popUp',
                status: status,
                id: good.id
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送弹卡命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            // 状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showPopUp',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    goodsId: good.id,
                    goodsName: good.title,
                    operator_type: 20,
                    status: status ? '1' : '0'
                }
            }).then((res) => {
                console.log('[control] 弹窗状态储存：', res);
                this.isPopUpId = good.id;
                this.isPopUpStatus = status;
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return false;
        },
        //弹卡
        imCard(good, status) {
            this.explain_id = good.id;
            const command = {
                command: 'card',
                status: status,
                id: good.id
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送弹卡命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            // 状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showPopCard',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    goodsId: good.id,
                    goodsName: good.title,
                    operator_type: status ? 5 : 6,
                    status: status ? '1' : '0'
                }
            }).then((res) => {
                console.log('[control] 弹卡状态储存：', res);
                this.isCardId = good.id;
                this.isCardStatus = status;
            }).catch((err) => {
                console.error('[control] err', err);
            });

            //如果开启弹卡，自动显示小黄车
            if (status) {
                this.switch_little_yellow_car_show = true;
                this.imLittleYellowCarCount();
            }
            return false;
        },
        //售空
        imSellOut(good, status) {
            this.explain_id = good.id;
            const command = {
                command: 'courseSellStatus',
                status: status,
                id: good.id
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送售空命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            // 状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showCourseSellStatus',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    goodsId: good.id,
                    goodsName: good.title,
                    operator_type: status ? 15 : 16,
                    status: status
                }
            }).then((res) => {
                console.log('[control] 售空状态储存：', res);
                // this.isSellOutId = good.id;
                good.isSellOutStatus = status;
                // this.isSellOutStatus = status;
            }).catch((err) => {
                console.error('[control] err', err);
            });

            return false;
        },
        //隐藏昵称
        imHideNickname() {
            const command = {
                command: 'hideNickname',
                status: this.switch_hide_nickname
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送隐藏昵称命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            //状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showNickName',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: this.switch_hide_nickname ? 9 : 10,
                    status: this.switch_hide_nickname ? '1' : '0'
                }
            }).then((res) => {
                console.log('[control] 隐藏昵称状态储存：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return false;
        },
        //全局禁言
        imAllSilence() {
            this.updateGroupProfile();
            // this.setGroupMemberRole();
            
        },
        //显示在线人数
        imOnlineCount() {
            if (!this.online_count_num) {
                this.$message.error('请输入初始在线人数');
                this.switch_online_people_show = false;
                return false;
            }
            this.switch_online_people_show = true;
            const command = {
                command: 'onlineCount',
                num: this.online_count_num,
                status: this.switch_online_people_show
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送显示在线人数命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            //状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showOnlineCount',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: 11,
                    num: this.online_count_num,
                    status: '0'
                }
            }).then((res) => {
                console.log('[control] 显示在线人数状态储存：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return false;
        },
        //显示小黄车
        imLittleYellowCarCount() {
            const command = {
                command: 'littleYellowCar',
                status: this.switch_little_yellow_car_show
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送显示小黄车命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            //状态储存
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showLittleYellowCar',
                params: {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: this.switch_little_yellow_car_show ? 12 : 13,
                    status: this.switch_little_yellow_car_show ? '1' : '0'
                }
            }).then((res) => {
                console.log('[control] 显示小黄车状态储存：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });


            //若是隐藏小黄车，则同步隐藏弹卡
            if (!this.switch_little_yellow_car_show) {
                this.isCardStatus = false;

                this.goodsList.forEach(element => {
                    if (element.id == this.isCardId) {
                        this.imCard(element, this.isCardStatus);
                    }
                });
                
            }
            


            return false;
        },
        /********************** 数字人评论 ****************************/
        //数字人评论随机发
        imDigitalHumanCommentRandom() {
            console.log('[control] 数字人评论随机发');
            if (this.randomUser) {
                this.imDigitalHumanCommentSendCommand(this.randomUser);
                if (!this.handoffUserType) {
                    this.init_digit_person_list(1);
                }
            }
        },
        //数字人评论
        imDigitalHumanCommentFrame() {
            console.log('[control] 数字人评论')
            this.isDigitalHumanComment = true;
        },
        //发布数字人评论
        imDigitalHumanCommentSendCommand(data, delay = true) {
            // 调用后端接口发 参数内容数组
            console.log('[control] data', data);
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 4,
                digital_id: data.id,
                digital_name: data.nick,
                digital_img: data.touxiang_img,
                digital_content: data.pinglun,
                identifier: 'R_' + data.id,
                msg: data.pinglun
            };
            const command = {
                liveId: this.live_id,
                command: 'sendMessage',
                params: params
            };
            if (this.operation_delay_num > 0 && delay) {
                setTimeout(() => {
                    sendCommandCmd(command).then((res) => {
                        console.log('[control] 数字人评论命令：', res);
                        this.$message.success('发送请求成功');
                    }).catch((err) => {
                        console.error('[control] err', err);
                    });
                }, this.operation_delay_num * 1000)
                return true;
            }
            sendCommandCmd(command).then((res) => {
                console.log('[control] 数字人评论命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return true;
        },
        //批量发布数字人评论
        imDigitalHumanCommentSendBatchCommand(array) {
            console.log('[control] array', array);
            // 调用后端接口发 参数id数组
            if (this.operation_delay_num > 0) {
                setTimeout(() => {
                    array.forEach((item) => {
                        setTimeout(() => {
                            this.imDigitalHumanCommentSendCommand(item, false)
                        }, 300)
                    })
                }, this.operation_delay_num * 1000)
                return true;
            }
            array.forEach((item) => {
                setTimeout(() => {
                    this.imDigitalHumanCommentSendCommand(item, false)
                }, 500)
            })
            return true;
        },
        //关闭数字人评论
        closeDigitalHumanCommentFrame() {
            this.isDigitalHumanComment = false;
        },
        /********************** 数字人下单 ****************************/
        //数字人下单随机发
        imDigitalHumanPayRandom() {
            this.init_digit_person_list(1);
            console.log('[control] 数字人下单随机发');
            if (this.randomUser) {
                this.imDigitalHumanPaySendCommand(this.randomUser);
                // if (!this.handoffUserType) {
                //     this.init_digit_person_list(1);
                // }
            }
        },
        //数字人下单
        imDigitalHumanPayFrame() {
            console.log('[control] 数字人下单')
            this.isDigitalHumanPay = true;
        },
        //发布数字人下单
        imDigitalHumanPaySendCommand(data, delay = true, cmd = true) {
            // 调用后端接口发 参数内容数组
            // console.log('[control] data', data);
            const command = {
                command: 'pay',
                nick: data.nick
            };
            if (this.operation_delay_num > 0 && delay) {
                setTimeout(() => {
                    sendCommand({
                        chartId: this.group_id,
                        command: JSON.stringify(command)
                    }).then((res) => {
                        console.log('[control] 发送下单飘字命令：', res);
                        this.$message.success('发送请求成功');
                    }).catch((err) => {
                        console.error('[control] err', err);
                    });
                }, this.operation_delay_num * 1000)
                return true;
            }
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送下单飘字命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });

            if (cmd) {
                const params = {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: 2,
                    digital_id: data.id,
                    digital_name: data.nick,
                    digital_img: data.touxiang_img,
                    digital_content: data.pinglun,
                    type: 0,
                    desc: data
                };
                sendCommandCmd({
                    liveId: this.live_id,
                    command: 'getPay',
                    params: params
                }).then((res) => {
                    console.log('[control] 发送数字人下单命令(内)：', res);
                }).catch((err) => {
                    console.error('[control] err', err);
                });
            }
            return true;
        },
        //批量发布数字人下单
        imDigitalHumanPaySendBatchCommand(array) {
            console.log('[control] array', array);
            // 调用后端接口发 参数id数组
            if (this.operation_delay_num > 0) {
                setTimeout(() => {
                    array.forEach((item) => {
                        this.imDigitalHumanPaySendCommand(item, false, false)
                    })
                }, this.operation_delay_num * 1000)
                return true;
            }
            array.forEach((item) => {
                this.imDigitalHumanPaySendCommand(item, false, false)
            })

            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 2,
                type: 1,
                list: array
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'getPay',
                params: params
            }).then((res) => {
                console.log('[control] 批量发送数字人下单命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return true;
        },
        //关闭数字人下单
        closeDigitalHumanPayFrame() {
            this.isDigitalHumanPay = false;
        },
        /********************** 数字人进场 ****************************/
        //数字人随机发
        imDigitalHumanSignInRandom() {
            this.init_digit_person_list(1);
            console.log('[control] 数字人随机发');
            if (this.randomUser) {
                this.imDigitalHumanSignInSendCommand(this.randomUser);
            }
        },
        //数字人进场
        imDigitalHumanSignInFrame() {
            console.log('[control] 数字人进场')
            this.isDigitalHumanSignIn = true;
        },
        //发布数字人进场
        imDigitalHumanSignInSendCommand(data, delay = true, cmd = true) {
            // 调用后端接口发 参数内容数组
            // console.log('[control] data', data);
            const command = {
                command: 'signIn',
                nick: data.nick,
                avatar: data.touxiang_img
            };
            if (this.operation_delay_num > 0 && delay) {
                setTimeout(() => {
                    sendCommand({
                        chartId: this.group_id,
                        command: JSON.stringify(command)
                    }).then((res) => {
                        console.log('[control] 发送数字人进场命令：', res);
                        this.$message.success('发送请求成功');
                    }).catch((err) => {
                        console.error('[control] err', err);
                    });
                }, this.operation_delay_num * 1000)
                return true;
            }
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送数字人进场命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            
            if (cmd) {
                const params = {
                    liveId: this.live_id,
                    operator_account: this.member_id,
                    operator_name: this.tutor_name,
                    operator_role: this.tutor_role,
                    operator_type: 1,
                    digital_id: data.id,
                    digital_name: data.nick,
                    digital_img: data.touxiang_img,
                    digital_content: data.pinglun,
                    type: 0,
                    desc: data
                };
                sendCommandCmd({
                    liveId: this.live_id,
                    command: 'getSignIn',
                    params: params
                }).then((res) => {
                    console.log('[control] 发送数字人进场命令(内)：', res);
                }).catch((err) => {
                    console.error('[control] err', err);
                });
            }
            return true;
        },
        //批量发布数字人进场
        imDigitalHumanSignInSendBatchCommand(array) {
            console.log('[control] array', array);
            // 调用后端接口发 参数id数组
            if (this.operation_delay_num > 0) {
                setTimeout(() => {
                    array.forEach((item) => {
                        this.imDigitalHumanSignInSendCommand(item, false, false)
                    })
                }, this.operation_delay_num * 1000)
                return true;
            }
            array.forEach((item) => {
                this.imDigitalHumanSignInSendCommand(item, false, false)
            })

            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 1,
                type: 1,
                list: array
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'getSignIn',
                params: params
            }).then((res) => {
                console.log('[control] 批量发送数字人进场命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return true;
        },
        //关闭数字人进场
        closeDigitalHumanSignInFrame() {
            this.isDigitalHumanSignIn = false;
        },
        /********************** 数字人浏览小黄车 ****************************/
        //数字人小黄车随机发
        imDigitalHumanCarRandom() {
            this.init_digit_person_list(1);
            console.log('[control] 数字人小黄车随机发');
            if (this.randomUser) {
                this.imDigitalHumanCarSendCommand(this.randomUser);
            }
        },
        //数字人小黄车
        imDigitalHumanCarFrame() {
            console.log('[control] 数字人购买')
            this.isDigitalHumanCar = true;
        },
        //发布数字人小黄车
        imDigitalHumanCarSendCommand(data, delay = true) {
            // 调用后端接口发 参数内容数组
            // console.log('[control] data', data);
            const command = {
                command: 'car',
                nick: data.nick
            };
            if (this.operation_delay_num > 0 && delay) {
                setTimeout(() => {
                    sendCommand({
                        chartId: this.group_id,
                        command: JSON.stringify(command)
                    }).then((res) => {
                        console.log('[control] 发送延迟数字人正在购买命令：', res);
                        this.$message.success('发送请求成功');
                    }).catch((err) => {
                        console.error('[control] err', err);
                    });
                }, this.operation_delay_num * 1000)
                return true;
            }
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送数字人正在购买命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 3,
                digital_id: data.id,
                digital_name: data.nick,
                digital_img: data.touxiang_img,
                digital_content: data.pinglun,
                type: 0,
                desc: data
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'getOnCar',
                params: params
            }).then((res) => {
                console.log('[control] 发布数字人正在购买命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return true;
        },
        //批量发布数字人小黄车
        imDigitalHumanCarSendBatchCommand(array) {
            console.log('[control] array', array);
            const command = {
                command: 'car',
                nick: array[0].nick,
                number: array.length
            };
            // 调用后端接口发 参数id数组
            if (this.operation_delay_num > 0) {
                setTimeout(() => {
                    // array.forEach((item) => {
                    //     this.imDigitalHumanCarSendCommand(item, false)
                    // })
                    sendCommand({
                        chartId: this.group_id,
                        command: JSON.stringify(command)
                    }).then((res) => {
                        console.log('[control] 发送多人正在购买命令：', res);
                        this.$message.success('发送请求成功');
                    }).catch((err) => {
                        console.error('[control] err', err);
                    });
                }, this.operation_delay_num * 1000)
                return true;
            }
            // array.forEach((item) => {
            //     this.imDigitalHumanCarSendCommand(item, false)
            // })
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送多人下单飘字命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });

            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 3,
                type: 1,
                list: array
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'getOnCar',
                params: params
            }).then((res) => {
                console.log('[control] 发送多人正在购买命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return true;
        },
        //关闭数字人浏览小黄车
        closeDigitalHumanCarFrame() {
            this.isDigitalHumanCar = false;
        },
        /********************** 关闭直播弹框 ****************************/
        //打开弹框
        imDigitalHumanEndLiveFrame() {
            console.log('[control] 打开弹框')
            this.isDigitalHumanEndLive = true;
        },
        //执行关闭直播
        imDigitalHumanEndLiveExecute() {
            sendEndLive({
                liveId: this.live_id
            }).then((res) => {
                console.log('[control] 执行关闭直播成功：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 5,
                status: true
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'offLive',
                params: params
            }).then((res) => {
                console.log('[control] 发送关闭直播命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return true;
        },
        //关闭弹框
        closeDigitalHumanEndLiveFrame() {
            this.isDigitalHumanEndLive = false;
        },
        //禁言
        silence(row) {
            row.is_silence = 1;
            this.msgList.map((item) => {
                if (item.id === row.id) {
                    item.is_silence = 1;
                    this.msgForbidList.push(item);
                }
                return item;
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 2,
                user: row,
                userIds: [row.id.toString()],
                time: 24 * 60 * 60
            };
            const command = {
                liveId: this.live_id,
                command: 'forbidUser',
                params: params
            };
            sendCommandCmd(command).then((res) => {
                console.log('[control] 禁言', row);
                console.log('[control] 用户禁言命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },
        //解除禁言
        endSilence(row) {
            row.is_silence = 0;
            this.msgForbidList = this.msgForbidList.filter(item => item.id !== row.id);
            this.msgList.map((item) => {
                if (item.id === row.id) {
                    item.is_silence = 0;
                }
                return item;
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 3,
                user: row,
                userIds: [row.id.toString()],
                time: 0
            };
            const command = {
                liveId: this.live_id,
                command: 'forbidUser',
                params: params
            };
            sendCommandCmd(command).then((res) => {
                console.log('[control] 解除禁言', row);
                console.log('[control] 用户解除禁言命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },
        //隐藏消息
        hideMsg(row) {
            row.is_hide = 1;
            this.msgList.map((item) => {
                if (item.no === row.no) {
                    item.is_hide = 1;
                }
                return item;
            });
            this.msgHideList.push(row);
            const command = {
                command: 'hideMsg',
                status: 1,
                no: row.no
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 1,
                user: row,
                status: 1,
                no: row.no
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'hideMsg',
                params: params
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },
        //显示消息
        showMsg(row) {
            row.is_hide = 0;
            this.msgHideList = this.msgHideList.filter(item => item.no !== row.no);
            console.log('显示', this.msgHideList);
            this.msgList.map(item => {
                if (item.no === row.no) {
                    item.is_hide = 0;
                }
                return item;
            });
            const command = {
                command: 'hideMsg',
                status: 0,
                no: row.no
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送显示消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 4,
                user: row,
                status: 0,
                no: row.no
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'hideMsg',
                params: params
            }).then((res) => {
                console.log('[control] 发送显示消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });

        },
        //发起抽奖
        choujiang(row) {
            row.is_hide = 1;
            this.msgList.map((item) => {
                if (item.no === row.no) {
                    item.is_hide = 1;
                }
                return item;
            });
            this.msgHideList.push(row);
            const command = {
                command: 'ChoujiangStatus',
                params: row.data,
                liveId: this.live_id,
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 17,
                digital_id: row.data.id,
                digital_name: row.data.title,
                digital_img: row.data.im_url,
                digital_content: row.data.countdown,
                user: row.data,
                status: 1,
                no: row.no
            };
        
            sendCommandCmd({
                liveId: this.live_id,
                command: 'ChoujiangStatus',
                params: params
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },
        //推送开奖状态
        lotteryMsg(row) {
            row.is_hide = 1;
            this.msgList.map((item) => {
                if (item.no === row.no) {
                    item.is_hide = 1;
                }
                return item;
            });
            this.msgHideList.push(row);
            const command = {
                command: 'KaiJiangStatus',
                params: row.data,
                liveId: this.live_id,
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 18,
                digital_id: row.data.id,
                digital_name: row.data.title,
                digital_img: row.data.im_url,
                digital_content: row.data.lott_state,
                user: row.data,
                status: 1,
                no: row.no
            };
            
            sendCommandCmd({
                liveId: this.live_id,
                command: 'KaiJiangStatus',
                params: params
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },
        //手动结束抽奖
        finish(row) {
            row.is_hide = 1;
            this.msgList.map((item) => {
                if (item.no === row.no) {
                    item.is_hide = 1;
                }
                return item;
            });
            this.msgHideList.push(row);
            const command = {
                command: 'FinishStatus',
                status: 1,
                params: row.data,
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });
            const params = {
                liveId: this.live_id,
                operator_account: this.member_id,
                operator_name: this.tutor_name,
                operator_role: this.tutor_role,
                operator_type: 19,
                digital_id: row.data.id,
                digital_name: row.data.title,
                digital_img: row.data.im_url,
                digital_content: row.data.status,
                user: row.data,
                status: 1,
                no: row.no
            };

            sendCommandCmd({
                liveId: this.live_id,
                command: 'FinishStatus',
                params: params
            }).then((res) => {
                console.log('[control] 发送隐藏消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },
        /********************** 评论隐藏数字人 ****************************/
        //隐藏数字人开关
        hideDigitMan() {
            if (this.switch_hide_digit_man) {
                this.msgList = this.msgList.map(item => {
                    if (item.type === 3 || item.type === 4) {
                        item.is_digit_man = 1;
                    }
                    return item;
                });
            } else {
                this.msgList = this.msgList.map(item => {
                    if (item.type === 3 || item.type === 4) {
                        item.is_digit_man = 0;
                    }
                    return item;
                });
            }
            console.log('[control] hideDigitMan', this.msgList);
            const params = {
                status: this.switch_hide_digit_man ? '1' : '0',
            };
            sendCommandCmd({
                liveId: this.live_id,
                command: 'showDigitMan',
                params: params
            }).then((res) => {
                console.log('[control] 发送显示消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
            return false;
        },


        /*******************     公告                 ********************* */

        gonggao_change(e) {

            console.log('gonggao_change:' + e);
            this.gonggao_textInput = e;
            this.gonggao_send();

        },


        gonggao_send() {
            
            if(this.gonggao_textInput.length > 0){
            }else{
                this.$message.success('公告文字不能为空');
                return ;
            }
            
            this.gonggao_show = true;
            const command = {
                command: 'sendGongGao',
                txt: this.gonggao_textInput,
                tutor_id: this.member_id,
                tutor_name: this.tutor_name,
                show: this.gonggao_show
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送显示消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });

            const a = {
                liveId: this.live_id,
                txt: this.gonggao_textInput,
                tutor_id: this.member_id,
                tutor_name: this.tutor_name,
                show: this.gonggao_show
            }

            sendCommandCmd({
                liveId: this.live_id,
                command: 'sendGongGao',
                params: a
            }).then((res) => {
                console.log('[control] 发送显示消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });

        },

        /********************      小黑板                   ************************/


        xiaoheiban_send() {
            
            if(this.imgList.length > 0 || this.xiaoheiban_textInput.length > 0){
            }else{
                this.$message.success('小黑板图片或文字不能为空');
                return ;
            }
            
            this.heiban_show = true;
            const command = {
                command: 'sendXiaoHeiBan',
                imgList: this.imgList,
                tutor_id: this.member_id,
                tutor_name: this.tutor_name,
                txt: this.xiaoheiban_textInput,
                show: this.heiban_show
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送显示消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });

            const a = {
                liveId: this.live_id,
                txt: this.xiaoheiban_textInput,
                imgList: this.imgList,
                tutor_id: this.member_id,
                tutor_name: this.tutor_name,
                 show: this.heiban_show
            }

            sendCommandCmd({
                liveId: this.live_id,
                command: 'sendXiaoHeiBan',
                params: a
            }).then((res) => {
                console.log('[control] 发送显示消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },


        xiaoheiban_send2() {
            this.heiban_show = false;
            const command = {
                command: 'sendXiaoHeiBan',
                imgList: this.imgList,
                tutor_id: this.member_id,
                tutor_name: this.tutor_name,
                show: this.heiban_show,
                txt: this.xiaoheiban_textInput,
            };
            sendCommand({
                chartId: this.group_id,
                command: JSON.stringify(command)
            }).then((res) => {
                console.log('[control] 发送显示消息命令：', res);
                this.$message.success('发送请求成功');
            }).catch((err) => {
                console.error('[control] err', err);
            });

            const a = {
                liveId: this.live_id,
                txt: this.xiaoheiban_textInput,
                imgList: this.imgList,
                tutor_id: this.member_id,
                tutor_name: this.tutor_name,
                show: this.heiban_show
            }

            sendCommandCmd({
                liveId: this.live_id,
                command: 'sendXiaoHeiBan',
                params: a
            }).then((res) => {
                console.log('[control] 发送显示消息命令(内)：', res);
            }).catch((err) => {
                console.error('[control] err', err);
            });
        },


        /******************************** 时间计数器 ************************************/
        getTime(date) {
            // const date = new Date()
            let year = this.bu0(date.getFullYear())
            let month = this.bu0(date.getMonth() + 1)
            let day = this.bu0(date.getDate())
            let hour = this.bu0(date.getHours())
            let minute = this.bu0(date.getMinutes())
            let second = this.bu0(date.getSeconds())

            // 秒
            this.index1 = +second[1]
            this.index2 = +second[0]
            // 分
            this.index3 = +minute[1]
            this.index4 = +minute[0]
            // 时
            this.index5 = +hour[1]
            this.index6 = +hour[0]
            //日
            this.index7 = +day[1]
            this.index8 = +day[0]
            //月
            this.index9 = +month[1]
            this.index10 = +month[0]
            //年
            this.index11 = +year[3]
            this.index12 = +year[2]
            this.index13 = +year[1]
            this.index14 = +year[0]

            // 倒计时
            const startTime = this.start_time.replace(' ', 'T');
            const targetTime = new Date(startTime).getTime();
            const now = new Date().getTime();
            const distance = targetTime - now;
            let seconds = Math.floor((distance / 1000) % 60);
            seconds = this.bu0(seconds);
            let minutes = Math.floor((distance / (1000 * 60)) % 60);
            minutes = this.bu0(minutes);
            let hours = Math.floor((distance / (1000 * 60 * 60)) % 24);
            hours = this.bu0(hours);
            let days = Math.floor(distance / (1000 * 60 * 60 * 24));
            days = this.bu0(days);
            // 秒
            this.pour1 = +seconds[1]
            this.pour2 = +seconds[0]
            // 分
            this.pour3 = +minutes[1]
            this.pour4 = +minutes[0]
            // 时
            this.pour5 = +hours[1]
            this.pour6 = +hours[0]
            //日
            this.pour7 = +days[1]
            this.pour8 = +days[0]

            // 累计时长
            const distances = now - targetTime;
            const secondss = this.bu0(Math.floor((distances / 1000) % 60));
            const minutess = this.bu0(Math.floor((distances / (1000 * 60)) % 60));
            const hourss = this.bu0(Math.floor((distances / (1000 * 60 * 60)) % 24));
            // 秒
            this.index01 = +secondss[1]
            this.index02 = +secondss[0]
            // 分
            this.index03 = +minutess[1]
            this.index04 = +minutess[0]
            // 时
            this.index05 = +hourss[1]
            this.index06 = +hourss[0]

            this.turnSecond(this.arr1.length, this.arr01.length)

        },
        bu0(num) {
            let str
            if (num < 10) str = `0${num}`
            else str = `${num}`
            return str.split('')
        },
        turnSecond(length, length0) {
            setInterval(() => {
                this.polling++
                //时间
                if (this.index1 === length - 1) {
                    // 通知前一位移动
                    this.turnOther(2, this.arr2.length)
                    this.index1 = -1
                }
                this.index1++
                //累计时长
                if (this.index01 === length0 - 1) {
                    // 通知前一位移动
                    this.turnOther(2, this.arr02.length, 1)
                    this.index01 = -1
                }
                this.index01++
                //倒计时
                if (this.pour1 === 0) {
                    // 通知前一位移动
                    this.turnOther(2, this.pourArr2.length, 2)
                    this.pour1 = 10
                }
                this.pour1--
            }, 1000)
        },
        turnOther(type, length, start = 0) {
            // type代表第几组数列，例如2，就是从右往左第二列
            if (start > 0) {
                if (start === 1) {
                    //累计时长
                    if (this[`index0${type}`] === length - 1) {
                        // 通知前一位移动
                        let next = type + 1
                        this.turnOther(next, this[`arr0${next}`].length, 1)
                        this[`index0${type}`] = -1
                    }
                    this[`index0${type}`]++
                } else if (start === 2) {
                    //倒计时
                    if (this[`pour${type}`] === 0) {
                        // 通知前一位移动
                        let next = type + 1
                        this.turnOther(next, this[`pourArr${next}`].length, 2)
                        if (type === 2 || type === 4) {
                            this[`pour${type}`] = 6
                        } else if (type === 6) {
                            this[`pour${type}`] = 3
                        } else if (type === 8) {
                            this[`pour${type}`] = 4
                        } else {
                            this[`pour${type}`] = 10
                        }
                    }
                    this[`pour${type}`]--
                }
            } else {
                //时间
                if (this[`index${type}`] === length - 1) {
                    // console.log('[control] ', type)
                    // 通知前一位移动
                    let next = type + 1
                    this.turnOther(next, this[`arr${next}`].length)

                    this[`index${type}`] = -1
                }
                this[`index${type}`]++
            }
        },


    }
}